package com.cqq.print.business.controller.order;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.cqq.auth.service.UserService;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.PageInfoBean;
import com.cqq.print.base.service.PBookCategoryService;
import com.cqq.print.base.service.bean.PBookCategoryBean;
import com.cqq.print.business.service.PArticleService;
import com.cqq.print.business.service.PBookService;
import com.cqq.print.business.service.POrderDetailService;
import com.cqq.print.business.service.POrderService;
import com.cqq.print.business.service.PTitleService;
import com.cqq.print.business.service.bean.PArticleBean;
import com.cqq.print.business.service.bean.PBookBean;
import com.cqq.print.business.service.bean.POrderBean;
import com.cqq.print.business.service.bean.POrderDetailBean;
import com.cqq.print.business.service.bean.POrderQueryBean;
import com.cqq.print.business.service.bean.PTitleBean;
import com.cqq.print.constant.Constant;
import com.cqq.print.constant.OrderType;
import com.cqq.pro.util.DateUtil;
import com.cqq.pro.util.ResponseUtil;


/**
 * 
 * @author CHENQQ
 *
 * 2016年3月31日
 */
@Controller(value = "dispatchController")
@RequestMapping(value = { "dispatch" }, method = {
		RequestMethod.POST,
		RequestMethod.GET })
public class DispatchController extends BaseController {
	
	@Autowired
	private POrderService pOrderService;
	@Autowired
	private POrderDetailService pOrderDetailService;
	@Autowired
	private PBookCategoryService pBookCategoryService;
	@Autowired
	private UserService userService;
	@Autowired
	private PBookService pBookService;
	@Autowired
	private PArticleService pArticleService;
	@Autowired
	private PTitleService pTitleService;

	
	@RequestMapping("listProduce")
	public ModelAndView listProduce(POrderQueryBean queryBean, Integer currentPage, Integer pageSize) {
		try {
			ModelAndView view = this.view("dispatch/dispatch-produce"); 
			queryBean.setOrderType(OrderType.ORDERTYPE_PRODUCE);
			queryBean.setForeman(FMContext.getLoginUser().getId());
			queryBean.setCheckStatus(Constant.ORDER_CHECKSTATUS_DONE);
			if (currentPage != null) {
				queryBean.setPageNo(currentPage);
			}
			if (pageSize != null) {
				queryBean.setPageSize(pageSize);
			}
			if (queryBean.getStartDateStr() != null && !queryBean.getStartDateStr().equals("")) {
				queryBean.setStartDate(DateUtils.parseDate(queryBean.getStartDateStr()+" 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			}
			if (queryBean.getEndDateStr() != null && !queryBean.getEndDateStr().equals("")) {
				queryBean.setEndDate(DateUtils.parseDate(queryBean.getEndDateStr()+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
			}
			if(StringUtils.isBlank(queryBean.getStartDateStr()) && StringUtils.isBlank(queryBean.getEndDateStr())){
				queryBean.setStartDate(DateUtil.getStartTime(DateUtil.getSkipDate(new Date(), -6)));
				queryBean.setEndDate(DateUtil.getEndTime(new Date()));
			}
			PageInfoBean<POrderBean> pageInfo = pOrderService.queryOrdersForDispatch(queryBean);
			view.addObject("pageInfo", pageInfo);
			return view;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return message(MESSAGE_TYPE_ERROR, "加载制作调度任务列表失败");
		}
		
	}
	
	@RequestMapping("listOutput")
	public ModelAndView listOutput(POrderQueryBean queryBean, Integer currentPage, Integer pageSize) {
		try {
			ModelAndView view = this.view("dispatch/dispatch-output"); 
			queryBean.setOrderType(OrderType.ORDERTYPE_OUTPUT);
			queryBean.setForeman(FMContext.getLoginUser().getId());
			queryBean.setCheckStatus(Constant.ORDER_CHECKSTATUS_DONE);
			if (currentPage != null) {
				queryBean.setPageNo(currentPage);
			}
			if (pageSize != null) {
				queryBean.setPageSize(pageSize);
			}
			if (queryBean.getStartDateStr() != null && !queryBean.getStartDateStr().equals("")) {
				queryBean.setStartDate(DateUtils.parseDate(queryBean.getStartDateStr()+" 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			}
			if (queryBean.getEndDateStr() != null && !queryBean.getEndDateStr().equals("")) {
				queryBean.setEndDate(DateUtils.parseDate(queryBean.getEndDateStr()+" 23:59:59", "yyyy-MM-dd HH:mm:ss"));
			}
			if(StringUtils.isBlank(queryBean.getStartDateStr()) && StringUtils.isBlank(queryBean.getEndDateStr())){
				queryBean.setStartDate(DateUtil.getStartTime(DateUtil.getSkipDate(new Date(), -6)));
				queryBean.setEndDate(DateUtil.getEndTime(new Date()));
			}
			
			PageInfoBean<POrderBean> pageInfo = pOrderService.queryOrdersForDispatch(queryBean);
			view.addObject("pageInfo", pageInfo);
			return view;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return message(MESSAGE_TYPE_ERROR, "加载输出调度任务列表失败");
		}
		
	}

	@RequestMapping("acceptOrder")
	public void acceptOrder(Integer oderId, HttpServletResponse response) {
		JSONObject json =  new JSONObject();
		if(oderId!=null){
			try{				
				if(oderId!=null){
					//更新订单的调度状态
					POrderBean pOrderBean = new POrderBean();
					pOrderBean.setId(oderId);
					pOrderBean.setStatus(Constant.ORDER_STATUS_ACCEPT);
					pOrderService.updateStatus(pOrderBean);
				}
				json.put("result", "success");
			}catch(Exception e){
				json.put("msg", "程序异常，请联系运维人员!");
				log.error(e.getMessage());
			}
		}else{
			json.put("result", "faild");
			json.put("msg", "oderId is null");
		}
		ResponseUtil.outJsonString(response, json);
	}
	
	

	@RequestMapping("toDispatchDetail")
	public String toDispatchDetail(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		String id = request.getParameter("orderId");
		if(id==null||id.trim().length()<=0){
			id = "0";
		}
		//订单信息
		POrderBean orderBean = pOrderService.queryOrderById(Integer.parseInt(id));
		//订单明细信息
		List<POrderDetailBean> listDetailBean = pOrderDetailService.queryDetailsByOrderId(Integer.parseInt(id));
		orderBean.setDetailCount(listDetailBean!=null?listDetailBean.size():0);
		//图书类型
		List<PBookCategoryBean> listPBBean = pBookCategoryService.queryBookCateGory();
		
		//版面-开本
		PBookBean bookBean = pBookService.selectByPrimaryKey(orderBean.getpBookId());
		//版面-正文
		PArticleBean articleBean = pArticleService.selectByPrimaryKey(orderBean.getpArticleId());
		//版面-标题
		PTitleBean titleBean = pTitleService.selectByPrimaryKey(orderBean.getpTitleId());
		
		out.put("bookBean",bookBean);
		out.put("articleBean",articleBean);
		out.put("titleBean",titleBean);
		out.put("listPBBean",listPBBean);
		out.put("listDetailBean",listDetailBean);
		out.put("orderBean",orderBean);
		return "dispatch/dispatchDetail";
	}
	
}
